import React, { Component, createContext } from "react";

// createContext用于做跨组件通信
// 调用以后返回context对象
const context = createContext();
//      提供者     消费者
const { Provider, Consumer } = context;

const Child2 = () => {
  return (
    <div>
      这是child2组件 -{" "}
      <Consumer>
        {(value) => {
          return (
            <>
              <span>{value.n}</span> -
              <button onClick={() => value.add()}>++</button>
            </>
          );
        }}
      </Consumer>
    </div>
  );
};

class Child1 extends Component {
  state = {};
  render() {
    return (
      <>
        <div>这是child1组件</div>

        <Child2 />
      </>
    );
  }
}

class App extends Component {
  state = {
    n: 1,
  };

  add = () => {
    this.setState({
      n: this.state.n + 1,
    });
  };

  render() {
    return (
      <Provider
        value={{
          n: this.state.n,
          add: this.add,
        }}
      >
        <h2>
          context上下文 - {this.state.n} -{" "}
          <button
            onClick={() => {
              this.setState({ n: 10 });
            }}
          >
            btn
          </button>
        </h2>
        <Child1 />
      </Provider>
    );
  }
}

export default App;
